package sfy.md.netty.netty;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

@ChannelHandler.Sharable     // #1
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    //现在通道连接上了,可以发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //连接之后立即发送一条消息
        System.out.println("外面客户端当前线程:"+Thread.currentThread().getName());


            ctx.writeAndFlush(Unpooled.copiedBuffer("_____wo shi ke hu duan xian zai  xiang ni fa song yi tiao xiao xi xi wang ni keiy  kandan wo fasong de xiaoxi ",
                    CharsetUtil.UTF_8));

                   //#2
    }

    //用十六进制记录接收到的消息
    @Override
    public void channelRead0(ChannelHandlerContext ctx,
                             ByteBuf in) {
        System.out.println("Client received: " + ByteBufUtil
                .hexDump(in.readBytes(in.readableBytes())));        //#3
    }

    //记录异常并关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,          //#4
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }


}

